//
//  MCCutDownButton.swift
//  StoreManage
//
//  Created by MC on 2018/8/29.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

// 倒计时按钮
typealias MCCutDownButtonClosure = () -> Void

class MCCutDownButton: UIButton {

    private var timer : Timer? = nil
    private var count : Int = 60
    
    public var clickedClosure : MCCutDownButtonClosure?
    
    var canRequest : Bool = false {
        didSet {
            if canRequest == true && isRequestSuccess == true {
                timeCutdown()
            }
        }
    }
    
    var isRequestSuccess : Bool = false {
        didSet {
            if canRequest == true && isRequestSuccess == true {
                timeCutdown()
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setTitleColor(UIColor.MCMain, for: UIControlState.normal)
        setTitle("| 获取验证码", for: UIControlState.normal)
        titleLabel?.font = UIFont.systemFont(ofSize: 14.0)
        addTarget(self, action: #selector(clickedClosureAction), for: UIControlEvents.touchUpInside)
        isEnabled = true
    }
    

    @objc private func clickedClosureAction() {
        clickedClosure!()
    }
    
    @objc private func timeCutdown() {
        
        if timer == nil {
            timer = Timer(timeInterval: 1.0, target: self, selector: #selector(buttonChanged), userInfo: nil, repeats: true)
            timer?.fire()
            RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes)
        }
    }
    
    @objc private func buttonChanged() {
        setTitle("\(count)s", for: UIControlState.normal)
        setTitleColor(UIColor.MCGray_middle, for: UIControlState.normal)
        isEnabled = false
        count -= 1
        if count < 0 {
            timer?.invalidate()
            timer = nil
            count = 60
            setTitle("重新获取", for: UIControlState.normal)
            setTitleColor(UIColor.MCMain, for: UIControlState.normal)
            isEnabled = true
        }
    }
    
    deinit {
        if timer != nil {
            if timer!.isValid {
                timer?.invalidate()
                timer = nil
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
